import { memo, useEffect, useState } from "react";
import { ProgrammeWrapper, ShareWrapper } from "./style";
import SearchItems, { type ISearchFormItem } from "@/commponts/SearchItems";
import { useAppDispatch, useAppSelector } from "@/store";
import {
  fetchExaminationListAction,
  fetchGetTaskListAction,
  fetchIllnessListAction,
} from "@/store/modules/patient";
import {
  Button,
  Checkbox,
  Divider,
  Message,
  Modal,
  Table,
} from "@arco-design/web-react";
import {
  IconEdit,
  IconDelete,
  IconDownload,
  IconPlus,
  IconSend,
} from "@arco-design/web-react/icon";
import {
  fetchDeleteProgrammeByIdAction,
  fetchExportProgrammeAction,
  fetchGetExaminationIdsAndTaskIdsById,
  fetchGetProgrammeList,
  fetchModifyProgrammeAction,
} from "@/store/modules/programme";
import dayjs from "dayjs";
import ModifyAndAdd from "./ModifyAndAdd";
import { number } from "echarts";
import downloadFile from "@/utils/exportData";
import { exportProgramme } from "@/service/modules/programme";

const ProgrammePage = () => {
  const dispatch = useAppDispatch();
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [isShare, setIsShare] = useState(false);
  const [selectedExaminationIds, setSelectedExaminationIds] = useState<
    string[]
  >([]);
  const [uniqueId, setUniqueId] = useState<number | null>(null);
  const [selectedTaskIds, setSelectedTaskIds] = useState<string[]>([]);
  const [isDelete, setIsDelete] = useState(false);
  const [mode, setMode] = useState<"edit" | "add">("edit");
  const [visible, setVisible] = useState(false);
  const [searchParams, setSearchParams] = useState({
    illnessName: "",
    programmeTitle: "",
  });
  const { examinationList, taskList } = useAppSelector(
    (state) => state.patient
  );
  const { illnessList } = useAppSelector((state) => state.patient);
  const { programmeList, total, shareList } = useAppSelector(
    (state) => state.programme
  );

  const getProgrammeList = async () => {
    await dispatch(fetchGetProgrammeList({ pageNum, pageSize }));
  };
  useEffect(() => {
    dispatch(fetchIllnessListAction());

    dispatch(fetchExaminationListAction());
    dispatch(fetchGetTaskListAction());
    getProgrammeList();
  }, [dispatch, pageNum, pageSize]);

  useEffect(() => {
    if (shareList) {
      setSelectedExaminationIds(shareList?.examinationIds);
      setSelectedTaskIds(shareList?.taskIds);
    }
  }, [shareList]);
  const searchItems: ISearchFormItem[] = [
    {
      type: "select",
      field: "illnessName",
      label: "病种名称",
      placeholder: "请选择病种名称",
      options: illnessList?.map((item) => {
        return { label: item.name, value: item.id };
      }),
    },
    {
      type: "input",
      field: "programmeTitle",
      label: "方案标题",
      placeholder: "请输入方案标题",
    },
  ];
  const handleSearch = (values: any) => {
    setSearchParams({
      illnessName: values.illnessName || "",
      programmeTitle: values.programmeTitle || 0,
    });
  };
  const getDetailInfo = async (id: number) => {
    await dispatch(fetchGetExaminationIdsAndTaskIdsById(id));
  };
  const handleVisible = (flag: boolean) => {
    setVisible(flag);
  };

  const SendCloseSelectedToSon = () => {
    setSelectedRowKeys([]);
  };
  const columns = [
    {
      title: "方案id",
      dataIndex: "programmeId",
    },
    {
      title: "病种名称",
      dataIndex: "illnessName",
    },
    {
      title: "方案标题",
      dataIndex: "programmeTitle",
    },
    {
      title: "方案内容",
      dataIndex: "programmeContent",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      render: (value: string) => {
        return <span>{dayjs(value).format("YYYY年MM月DD日")}</span>;
      },
    },
    {
      title: "操作",
      dataIndex: "movement",
      render: (_: any, record: any) => {
        return (
          <div className="movement_btn">
            <div>
              <Button
                type="text"
                icon={<IconSend />}
                onClick={() => {
                  setUniqueId(record.programmeId);
                  setIsShare(true);
                  getDetailInfo(record.programmeId);
                }}
              >
                项目分配
              </Button>
            </div>
            <div>
              <Button
                type="text"
                icon={<IconEdit />}
                onClick={() => {
                  setVisible(true);
                }}
              >
                修改
              </Button>

              <Button
                type="text"
                icon={<IconDelete />}
                onClick={() => {
                  setIsDelete(true);
                  setSelectedRowKeys([record.programmeId]);
                }}
              >
                删除
              </Button>
            </div>
          </div>
        );
      },
    },
  ];
  const data = programmeList?.map((item) => {
    const illness = illnessList?.find((val) => val.id === item.illnessId);
    return {
      programmeId: item.id,
      illnessName: illness?.name || "",
      programmeTitle: item.title,
      programmeContent: item.content,
      createTime: item.createTime,
    };
  });

  const filterData = data.filter((item) => {
    const matchIllnessName =
      !searchParams.illnessName ||
      item?.illnessName.includes(searchParams.illnessName);
    const matchProgrammeTitle =
      !searchParams.programmeTitle ||
      item?.programmeTitle.includes(searchParams.programmeTitle);
    return matchIllnessName && matchProgrammeTitle;
  });
  const onSelectChange = (newSelectedRowKeys: any[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
    // console.log(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const toggleSelectExamination = (id: string) => {
    setSelectedExaminationIds((prev) => {
      console.log(prev);
      return prev.includes(id)
        ? prev.filter((item) => item !== id)
        : [...prev, id];
    });
  };
  const toggleSelectTask = (id: string) => {
    setSelectedTaskIds((prev) => {
      return prev.includes(id)
        ? prev.filter((item) => item !== id)
        : [...prev, id];
    });
  };
  // console.log(selectedExaminationIds);
  const examinationColumns = [
    {
      title: "编号",
      dataIndex: "examinationId",
    },
    {
      title: "检查项目",
      dataIndex: "examinationName",
    },
    {
      title: "是否分配",
      render: (_: string, record: any) => {
        // console.log(record);

        return (
          <Checkbox
            checked={selectedExaminationIds?.includes(record.examinationId)}
            onChange={() => toggleSelectExamination(record.examinationId)}
          />
        );
      },
    },
  ];
  const examinationData = examinationList?.map((item) => {
    return {
      examinationId: item.id,
      examinationName: item.name,
    };
  });

  const taskColumns = [
    {
      title: "编号",
      dataIndex: "taskId",
    },
    {
      title: "训练项目",
      dataIndex: "taskName",
    },
    {
      title: "是否分配",
      render: (_: string, record: any) => {
        // console.log(record);
        return (
          <Checkbox
            checked={selectedTaskIds?.includes(record.taskId)}
            onChange={() => toggleSelectTask(record.taskId)}
          />
        );
      },
    },
  ];
  const taskData = taskList?.map((item) => {
    return {
      taskId: item.id,
      taskName: item.title,
    };
  });

  const handleShareProgramme = async () => {
    await dispatch(
      fetchModifyProgrammeAction({
        id: uniqueId || null,
        examinationIds: selectedExaminationIds.map(Number),
        taskIds: selectedTaskIds.map(Number),
      })
    );
  };
  const deleteProgramme = async () => {
    await dispatch(fetchDeleteProgrammeByIdAction(selectedRowKeys));
    setIsDelete(false);
    setSelectedRowKeys([]);
    Message.success("删除成功");
    getProgrammeList();
  };
  return (
    <ProgrammeWrapper>
      <Modal
        title="方案制定"
        visible={isShare}
        onCancel={() => setIsShare(false)}
        onOk={() => {
          handleShareProgramme();
          setIsShare(false);
        }}
      >
        <ShareWrapper>
          <h3>检查项目分配</h3>
          <Table
            rowKey={(record) => record.examinationId}
            style={{ userSelect: "none" }}
            data={examinationData}
            columns={examinationColumns}
            // rowSelection={{
            //   checkAll: false,
            //   fixed: false,
            // }}
            pagination={false}
            scroll={{
              y: 200,
            }}
          />
          <Divider />
          <h3>康复项目训练项目分配</h3>
          <Table
            rowKey={(record) => record.taskId}
            style={{ userSelect: "none" }}
            data={taskData}
            columns={taskColumns}
            pagination={false}
            scroll={{
              y: 200,
            }}
          />
        </ShareWrapper>
      </Modal>
      <Modal
        visible={isDelete}
        title="警告"
        onCancel={() => {
          setIsDelete(false);
          setSelectedRowKeys([]);
        }}
        onOk={deleteProgramme}
      >
        <p>你确定要删除id为{selectedRowKeys.join(",")}的方案吗</p>
      </Modal>
      <ModifyAndAdd
        getProgrammeList={getProgrammeList}
        SendCloseSelectedToSon={SendCloseSelectedToSon}
        mode={mode}
        visible={visible}
        handleVisible={handleVisible}
        id={uniqueId}
      />
      <SearchItems items={searchItems} onSearch={handleSearch} />
      <div className="centerWrapper">
        <Button
          icon={<IconPlus />}
          type="primary"
          onClick={() => {
            setMode("add");
            setVisible(true);
          }}
          className="btn"
        >
          新增
        </Button>
        <Button
          disabled={selectedRowKeys.length < 1}
          icon={<IconEdit />}
          type="primary"
          status="success"
          className="btn"
          onClick={() => {
            setMode("edit");
            setUniqueId(Number(selectedRowKeys[selectedRowKeys.length - 1]));
            setVisible(true);
          }}
        >
          修改
        </Button>
        <Button
          // disabled={selectedRowKeys.length < 1}
          className="btn"
          icon={<IconDelete />}
          type="primary"
          status="danger"
          disabled={selectedRowKeys.length < 1}
          onClick={() => setIsDelete(true)}
        >
          删除
        </Button>
        <Button
          className="btn"
          icon={<IconDownload />}
          type="primary"
          status="warning"
          onClick={async () => {
            // Modal.warning({
            //   title: "通知",
            //   content: "导出接口崩了，正在维修中。。。",
            //   okText: "关闭",
            // });
            const programmeList = await exportProgramme({ pageNum, pageSize });
            downloadFile(
              programmeList,
              `方案列表_${dayjs().format("YYYY-MM-DD")}.xlsx`
            );
            Message.success("导出成功");
          }}
        >
          导出
        </Button>
      </div>
      <div className="table">
        <Table
          rowSelection={rowSelection}
          columns={columns}
          data={filterData}
          rowKey={(record) => record.programmeId}
          pagination={{
            total,
            sizeOptions: [10, 20, 30],
            showJumper: true,
            pageSize,
            current: pageNum,
            showTotal: (total) => `共${total}条`,
            sizeCanChange: true,
            onChange: (current, pageSize) => {
              setPageNum(current);
              setPageSize(pageSize);
            },
            style: {
              marginRight: "15px",
            },
          }}
        />
      </div>
    </ProgrammeWrapper>
  );
};
export default memo(ProgrammePage);
